import os, sys, logging
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.1')

from google.appengine.ext.db import djangoforms
from models import Project, Milestone, Committer, Holiday, Obligation
from django.db import models
from django import forms
import datetime
import re
from google.appengine.ext.db.djangoforms import ModelChoiceField

class DateListField(forms.CharField):
    def clean(self, value):
        new_value = super(DateListField, self).clean(value)
        datetimes = []
        if new_value.find('datetime') != -1:
            r = re.compile("datetime.datetime\((\d+), (\d+), (\d+)")
            for dates in r.findall(new_value):
                datetimes.append(datetime.datetime(int(dates[0]), int(dates[1]), int(dates[2])))
            return datetimes
        dates = new_value.split(',')
        for date in dates:
            date = date.replace(' ', '')
            parts = date.split('/')
            if len(parts) != 3:
                raise djangoforms.forms.ValidationError('Dates must be in the form of MM/DD/YYYY')
            datetimes.append(datetime.datetime(int(parts[2]), int(parts[0]), int(parts[1])))
        return datetimes

# class MultipleCommitterField(MultipleChoiceField):
#     def clean(self, value):
#         new_value = super(MultipleCommitterField, self).clean(value)
#         return new_value

class ProjectForm(djangoforms.ModelForm):
    class Meta:
        model = Project
        exclude = ('latest_issue_update', 'contributors', 'num_tickets')

class MilestoneForm(djangoforms.ModelForm):
    project = ModelChoiceField(Project, widget=forms.HiddenInput)
    
    def clean_name(self):
        data = self.data['name']
        if 'Milestone-' not in data:
            raise djangoforms.forms.ValidationError("Name must take form of Milestone-X.x")
        return data
        
    def clean_due(self):
        data = self.data['due']
        date = datetime.date(*[int(d) for d in data.split('-')])
        if date.weekday() > 4:
            raise djangoforms.forms.ValidationError("Milestone date must be a weekday")
        return date
    
    class Meta:
        model = Milestone

class CommitterForm(djangoforms.ModelForm):
    class Meta:
        model = Committer
        
class HolidayForm(djangoforms.ModelForm):
    class Meta:
        model = Holiday
        
def get_committers(self):
    return [(str(c.first_alias()), str(c.first_alias())) for c in Committer.all()]

class ObligationForm(djangoforms.ModelForm):    
    def __init__(self, *args, **kwargs):
        super(ObligationForm, self).__init__(*args, **kwargs)
        choices = [(str(c.first_alias()), str(c.first_alias())) for c in Committer.all()]
        self.fields['committers'] = forms.MultipleChoiceField(choices=choices)
    
    class Meta:
        model = Obligation